package zoran.wang.tools;

import zoran.wang.tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树工具类，包含：
 * 二叉树生成器、二叉树层序遍历
 *
 * @author wangzhuo
 * @time 2025-04-10-16:30
 */
public class BinaryTreeTools {

    /**
     * 根据可变数组构造二叉树
     *
     * @param values 可变参数数组，按层次遍历顺序，null表示空节点
     * @return 构造好的二叉树根节点
     */
    public static TreeNode buildTree(Integer... values) {
        if (values == null || values.length == 0 || values[0] == null) {
            return null;
        }

        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int index = 1;
        while (!queue.isEmpty() && index < values.length) {
            TreeNode current = queue.poll();

            // 处理左子节点
            if (index < values.length && values[index] != null) {
                current.left = new TreeNode(values[index]);
                queue.offer(current.left);
            }
            index++;

            // 处理右子节点
            if (index < values.length && values[index] != null) {
                current.right = new TreeNode(values[index]);
                queue.offer(current.right);
            }
            index++;
        }

        return root;
    }

    // 层次遍历打印二叉树
    public static void levelOrderTraversal(TreeNode root) {
        if (root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 1;

        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                System.out.println(node.val + " in level " + depth);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            depth++;
        }
    }
}
